package com.example.studentregistration.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.studentregistration.pojo.Users;
import com.example.studentregistration.service.UserService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

//用户控制器类
@RestController
@RequestMapping("/api")
public class UserController {
    //注入UserService实例
    @Autowired
    private UserService userService;

    private LineCaptcha lineCaptcha;

    @PostMapping("/user")
    public Result<?> insertUser(@RequestBody Users user) {
        System.out.println(user);
        return userService.insertUser(user);
    }

    //修改用户信息
    @PutMapping("/user")
    public Result<?> updateUser(@RequestBody Users user) {
        return userService.updateUser(user);
    }

    //删除用户
    @DeleteMapping("/user/{id}")
    public Result<?> deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }


    //查询所有用户
    @GetMapping("/user")
    public Result<?> queryAllUsers(@RequestParam(defaultValue = "1") Integer currentPage,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        Page page = userService.queryAllUsers(currentPage, pageSize);
        PageInfo<Object> pointerInfo = new PageInfo<>(page);
        return Result.success(pointerInfo);
    }

    //提供手机号查询用户
    @GetMapping("/user/{phone}")
    public Result<?> queryUserByPhone(@PathVariable String phone) {
        return userService.queryUserByPhone(phone);
    }

    //提供用户名查询用户
    @GetMapping("/user/username/{username}")
    public Result<?> queryUserByName(@PathVariable String username) {
        return userService.queryUserByName(username);
    }


    //
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        //定义图形验证码长和宽
        lineCaptcha = CaptchaUtil.createLineCaptcha(125, 45);
        lineCaptcha.setBackground(new Color(181, 238, 218));
        //写出数据到流
        try {
            ServletOutputStream os = response.getOutputStream();
            //输出图片到浏览器
            lineCaptcha.write(os);
            //释放资源
            os.flush();
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //用户登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> user) {
        //获取用户输入的验证码
        String code = user.get("code");
        System.out.println("验证码"+code);
        //验证码验证
        if (!lineCaptcha.verify(code)) {
            return Result.fail("验证码错误");
        }
//        return userService.login(user.get("username"),user.get("password"));
        return userService.login(user.get("phone"),user.get("password"));

    }

    //导出用户信息
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        userService.exportExcel(response);
    }

    //文件导入
    @PostMapping("/import")
    public Result<?> importExcel( MultipartFile file) throws IOException {
        //获取文件流输入对象
        InputStream is = file.getInputStream();
        //读取流
        ExcelReader reader = ExcelUtil.getReader(is);
        List<Users> list = reader.readAll(Users.class);
        //批处理
        try {
            list.stream().forEach(user ->
                userService.insertUser(user));
        } catch (Exception e) {
            Result.fail("导入失败");
        }
        return Result.success("导入成功");
    }

    //批量删除
    @DeleteMapping("/batch")
    public Result<?> batchDeleteUser(@RequestBody List<Integer> ids) {
        try {
            int deletedCount = userService.batchDeleteUser(ids);
            return Result.success("成功删除 " + deletedCount + " 个用户");
        } catch (Exception e) {
            return Result.fail("批量删除失败: " + e.getMessage());
        }
    }


}
